const { BrowserWindow, ipcMain } = require("electron");
const logger = require("./log.cjs");
const { IconWindowInit } = require("./iconWindow.cjs");
const { searchChatWindowInit } = require("./searchChatWindow.cjs");
const windowManager = require("./windowMamager.cjs");
const { isDev } = require("./utils.cjs");
const path = require("path");
const { setWindowInit } = require("./setting.cjs");
let win = null;
const createWindow = () => {
  win = new BrowserWindow({
    width: 1000,
    height: 640,
    center: true,
    skipTaskbar: false,
    resizable: false,
    transparent: true,
    alwaysOnTop: false,
    frame: true,
    show: false,
    autoHideMenuBar: true,
    webPreferences: {
      contextIsolation: false,
      webSecurity: false,
      devTools: true,
      //  渲染进程 开启node模块，使得JS中可以使用node的model
      nodeIntegration: true,
      // 开启 remote 模块
      enableBlinkFeatures: true,
      enableRemoteModule: true,
      // 控制上下文隔离
      // contextIsolation:false,
    },
  });
  win.loadURL(
    isDev()
      ? "http://localhost:5173/#/login"
      : `file://${path.join(__dirname, "../dist/index.html")}#/login`
  );
  win.on("ready-to-show", () => {
    win.show(); // 初始化后再显示
  });
  listenIsLogin();
  listenIsLogout();
  // win.webContents.openDevTools();
  return win;
};

function listenIsLogin() {
  // ipcMain.handle("isLogin", function () {
    win.hide();
    IconWindowInit();
    searchChatWindowInit();
    setWindowInit();
  // });

  ipcMain.handle("isLoginUpdate", function () {
    win.hide();
    let iconWin = windowManager.get("iconWin");
    let setWin = windowManager.get("settingWin");
    let search = windowManager.get("searchWin");
    search.show();
  });
}

function listenIsLogout() {
  ipcMain.handle("isLogout", function () {
    win.show();
    win.webContents.send("sysLogout", {
      sysLogout: true,
    });
    let setWin = windowManager.get("settingWin");
    setWin.hide();
    // loginWindowInit();
    // searchChatWindowInit();
    // setWindowInit();
  });
}

function loginWindowInit() {
  try {
    win = createWindow();
  } catch (error) {
    logger.error(error);
  }
}

module.exports = {
  loginWindowInit,
};
